package com.xuxiangyang.competitionsystem.tools;

import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.data.NumbericRenderData;
import com.deepoove.poi.data.TextRenderData;
import com.deepoove.poi.policy.ListRenderPolicy;
import com.xuxiangyang.competitionsystem.entities.TemplateDate;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Component
public class FileUtils {

    public String downloadFile(HttpServletRequest request, String urlPath, String where, String downloadDir, String fileName) {
        File file = null;
        String retUrl = request.getScheme() + "://" + request.getServerName()
                + ":" + request.getServerPort() + request.getContextPath() + "/" + downloadDir + fileName;;
        try {
            // 统一资源
            URL url = new URL(urlPath);
            // 连接类的父类，抽象类
            URLConnection urlConnection = url.openConnection();
            // http的连接类
            HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
            //设置超时
            httpURLConnection.setConnectTimeout(1000*5);
            //设置请求方式，默认是GET
//            httpURLConnection.setRequestMethod("POST");
            // 设置字符编码
            httpURLConnection.setRequestProperty("Charset", "UTF-8");
            // 打开到此 URL引用的资源的通信链接（如果尚未建立这样的连接）。
            httpURLConnection.connect();
            // 文件大小
            int fileLength = httpURLConnection.getContentLength();

            // 控制台打印文件大小
            System.out.println("您要下载的文件大小为:" + fileLength / (1024 * 1024) + "MB");

            // 建立链接从请求中获取数据
            URLConnection con = url.openConnection();
            BufferedInputStream bin = new BufferedInputStream(httpURLConnection.getInputStream());
            // 指定存放位置(有需求可以自定义)
            String path = where + downloadDir + fileName;
            file = new File(path);
            // 校验文件夹目录是否存在，不存在就创建一个目录
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }

            OutputStream out = new FileOutputStream(file);
            int size = 0;
            int len = 0;
            byte[] buf = new byte[2048];
            while ((size = bin.read(buf)) != -1) {
                len += size;
                out.write(buf, 0, size);
                // 控制台打印文件下载的百分比情况
                System.out.println("下载了-------> " + len * 100 / fileLength + "%\n");
            }
            // 关闭资源
            bin.close();
            out.close();
            System.out.println("文件下载成功！");
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            System.out.println("文件下载失败！");
        } finally {
            return retUrl;
        }

    }

//    智能排版
    public String typesetting(TemplateDate templateDate,String templateName, String outName, String outPath) throws IOException {
        InputStream inputStream = new FileInputStream(new File("src/main/resources/static/templates/" + templateName));
        Map<String, Object> data = new HashMap<>();
        //作品编号
        data.put("groupId", templateDate.getGroupId());
        //作品名称
        data.put("compName", templateDate.getCompName());
        //作品大类
        data.put("category", templateDate.getCategory());
        //竞赛名称
        data.put("groupName", templateDate.getGroupName());
        //作品简介
        data.put("introduction", templateDate.getIntroduction());
        //市场需求分析
        data.put("innovation", templateDate.getInnovation());
        //技术路线
        data.put("technology", templateDate.getTechnology());
        //研究进度
        data.put("progress", templateDate.getProgress());
        //预计成果
        data.put("result", templateDate.getResult());
        //经费预算
        data.put("budget", templateDate.getBudget());
        //制作平台
        data.put("proPlatform", templateDate.getProPlatform());
        //运行平台
        data.put("runPlatform", templateDate.getRunPlatform());
        //制作工具
        data.put("tools", templateDate.getTools());
        //指导老师
        data.put("teacherName", templateDate.getTeacherName());
        //负责人
        data.put("sponsor", templateDate.getSponsor());
        //学校
        data.put("schoolName", templateDate.getSchoolName());
        //参考作品
        //对某个元素设置自适应生成对应的行数据
        ListRenderPolicy policy = new ListRenderPolicy();
        Configure config = Configure.newBuilder()
                .bind("name", policy).build();
        String[] teammatesSplit = templateDate.getTeammates().split(",");
        data.put("teammates",  new NumbericRenderData(NumbericRenderData.FMT_DECIMAL, new ArrayList<TextRenderData>() {
            {
                for (String teammate: teammatesSplit) {
                    add(new TextRenderData(teammate));
                }
            }
        }));
        //备注
        data.put("remark", templateDate.getRemark());
        XWPFTemplate template = XWPFTemplate.compile(inputStream, config)
                .render(data);
        FileOutputStream out;
        out = new FileOutputStream(new File(outPath + outName));
        template.write(out);
        out.flush();
        out.close();
        template.close();
        return "";
    }

    public String getUrl(HttpServletRequest request,String directory,String fileName) {
        return request.getScheme() + "://" + request.getServerName()
                + ":" + request.getServerPort() + request.getContextPath() + "/" + directory +fileName;
    }

    public String storage(HttpServletRequest request, MultipartFile file,String realPath, String fileName) {
        String fileUrl = "";
        if (Objects.isNull(file) || file.isEmpty()) {
            System.out.println("文件为空");
        }
        try {
            //写入目的地
            org.apache.commons.io.FileUtils.writeByteArrayToFile(new File(realPath + fileName),
                    file.getBytes());
        } catch (Exception e) {
            System.out.println("error");
        }
//        fileUrl = url + fileName;
        fileUrl = this.getUrl(request,"static/temporary/",fileName);
        return fileUrl;
    }
}
